<template>
  <el-row :gutter="20">
    <!-- 左侧树形结构 -->
    <el-col :span="8">
      <el-tree ref="tree" :data="treeData" show-checkbox default-expand-all node-key="id" :props="defaultProps"/>
    </el-col>
    <!-- 右侧表单 -->
    <el-col :span="16">
      <el-form :model="form" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="时间范围">
              <el-date-picker
                  v-model="dateRange"
                  size="small"
                  style="width: 240px"
                  value-format="yyyy-MM-dd"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item>
              <el-button type="primary" @click="handleUpload" :disabled="loading">数据上传</el-button>
              <el-button type="danger" @click="handleDelete" :disabled="loading">数据删除</el-button>
              <el-button @click="handleCancel">取 消</el-button>
            </el-form-item>
          </el-col>
          <!-- 显示进度条 -->
          <el-progress v-if="loading" :text-inside="true" :stroke-width="20" :percentage="progress" status="active" />
        </el-row>
      </el-form>
    </el-col>
  </el-row>
</template>
<script>
import {queryEquip, queryPoint} from "@/api/equip";
import {deleteRaw, progress, uploadRaw} from "@/api/raw";

export default {
  data() {
    return {
      // 生成的树形数据
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      equipmentList: null,
      pointList: null,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      loading: false,
      progress: 0
    }
  },
  created() {
    let time = this.parseTime(new Date().getTime(), '{y}-{m}-{d}');
    this.dateRange = [time, time];
    this.initData();
  },
  methods: {
    initData() {
      // 使用 Promise.all 来并行执行两个请求
      Promise.all([queryEquip(), queryPoint()])
          .then(([equipRes, pointRes]) => {
            // 设置设备和测点数据
            this.equipmentList = equipRes.data;
            this.pointList = pointRes.data;
            // 在数据都加载完后生成树形数据
            this.buildTreeData();
          })
          .catch(error => {
            console.error('数据加载失败:', error);
          });
    },
    // 树形数据生成函数
    buildTreeData() {
      const equipmentMap = new Map();
      // 构建设备树的基本结构
      this.equipmentList.forEach(equip => {
        equipmentMap.set(equip.equipmentId, {
          id: equip.equipmentId,
          code: equip.equipmentCode,
          label: equip.equipmentName,
          children: [],
        });
      });

      // 根据 parentId 构建父子关系
      const tree = [];
      this.equipmentList.forEach(equip => {
        const node = equipmentMap.get(equip.equipmentId);
        if (equip.parentId) {
          const parent = equipmentMap.get(equip.parentId);
          if (parent) {
            parent.children.push(node);
          }
        } else {
          tree.push(node); // 顶级节点
        }
      });

      // 绑定测点到对应设备
      this.pointList.forEach(point => {
        const equipment = this.equipmentList.find(equip => equip.equipmentCode === point.equipmentCode);
        if (equipment) {
          const parentNode = equipmentMap.get(equipment.equipmentId);
          if (parentNode) {
            parentNode.children.push({
              id: point.pointCode,
              label: point.pointName, // 测点名称
              isPoint: true, // 用于标识这是测点
            });
          }
        }
      });
      // 树形数据赋值
      this.treeData = tree;
    },
    handleUpload() {
      if (!this.mergeForm()) return;
      uploadRaw(this.form).then(res => {
        this.progress = 0;
        this.loading = true;
        // 提交成功，开始轮询获取后端处理进度
        this.startPollingProgress(res.data.taskId);
      })
    },
    handleCancel() {
      this.$emit('cancel');
    },
    handleDelete() {
      if (!this.mergeForm()) return;
      let that = this;
      this.$modal.confirm('是否确认要删除本地原始数据？').then(function () {
        deleteRaw(that.form).then(res => {
          that.progress = 0;
          that.loading = true;
          // 提交成功，开始轮询获取后端处理进度
          that.startPollingProgress(res.data.taskId);
        })
      }).then(() => {
        that.$emit('reload');
        that.$modal.msgSuccess("删除成功");
      }).catch((e) => {
        console.log(e)
      });
    },
    mergeForm() {
      // 获取选中的节点对象（包含设备或测点）
      const checkedNodes = this.$refs.tree.getCheckedNodes();
      // 获取选中的测点编码(id)
      const selectedPointCodes = checkedNodes.filter(item => item.isPoint).map(item => item.id);
      if (this.isNullOrEmpty(selectedPointCodes)) {
        this.$modal.msgError("请选择左侧测点");
        return false;
      }
      if (this.isNullOrEmpty(this.dateRange)) {
        this.$modal.msgError("请选择时间范围");
        return false;
      }
      // console.log('选中的测点编码:', selectedPointCodes);
      this.form.pointCode = selectedPointCodes.join(',');
      this.from = this.addDateRange(this.form, this.dateRange);
      return true;
    },
    // 开始轮询获取后端的处理进度
    startPollingProgress(taskId) {
      this.pollingInterval = setInterval(() => {
        progress(taskId).then(res => {
          const progress = res.data.progress;
          this.progress = progress;
          if (progress >= 100) {
            clearInterval(this.pollingInterval);
            this.$modal.msgSuccess("处理完成!");
            this.loading = false;
          }
        }).catch(error => {
          console.error("获取进度失败", error);
        });
      }, 100); // 每100毫秒请求一次进度
    }
  }
}
</script>
<style scoped>

</style>